package com.example.uibestpractice;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.uibestpractice.viewholder.GetMessageViewHolder;
import com.example.uibestpractice.viewholder.SendMessageViewHolder;

import java.util.ArrayList;

public class MessageRecyclerAdapter extends RecyclerView.Adapter {
    ArrayList<Message> messages;

    public MessageRecyclerAdapter(ArrayList<Message> messages) {
        this.messages = messages;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder;
        View view;
       if (viewType == Message.GET_MESSAGE){
           view = LayoutInflater.from(parent.getContext()).inflate(R.layout.get_message,parent,false);
          viewHolder = new GetMessageViewHolder(view);
       }else {
           view = LayoutInflater.from(parent.getContext()).inflate(R.layout.send_message,parent,false);
           viewHolder = new SendMessageViewHolder(view);
       }
       return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        Message message = messages.get(position);
        if(message.getType() == Message.GET_MESSAGE){
            ((GetMessageViewHolder) holder).getMessage().setText(message.getMsg());
        }else{
            ((SendMessageViewHolder) holder).getMessage().setText(message.getMsg());
        }
    }

    @Override
    public int getItemViewType(int position) {
        //根据message的类型进行输入和修改
        Message message = messages.get(position);
        if(message.getType() == Message.GET_MESSAGE){
            return  Message.GET_MESSAGE;
        }else{
            return Message.SENT_MESSAGE;
        }
    }

    @Override
    public int getItemCount() {
        return messages.size();
    }
}
